#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# QQ: 34538980@qq.com
# Jekkay Hu, 2013.5.5
# ///////////////////////////////////////////////////////////////////
#                            _ooOoo_                               //
#                           o8888888o                              //
#                           88" . "88                              //
#                           (| ^_^ |)                              //
#                           O\  =  /O                              //
#                        ____/`---'\____                           //
#                      .'  \\|     |//  `.                         //
#                     /  \\|||  :  |||//  \                        //
#                    /  _||||| -:- |||||-  \                       //
#                    |   | \\\  -  /// |   |                       //
#                    | \_|  ''\---/''  |   |                       //
#                    \  .-\__  `-`  ___/-. /                       //
#                  ___`. .'  /--.--\  `. . ___                     //
#                ."" '<  `.___\_<|>_/___.'  >'"".                  //
#              | | :  `- \`.;`\ _ /`;.`/ - ` : | |                 //
#              \  \ `-.   \_ __\ /__ _/   .-` /  /                 //
#        ========`-.____`-.___\_____/___.-`____.-'========         //
#                             `=---='                              //
#        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
#             佛祖保佑       永无BUG        运行正常                   //
#     -------------------------------------------------------      //
#               QQ: 34538980@qq.com                                //
#               博客: http://www.easysb.cn                          //
#               Jekkay Hu, 2013.5.5                                //
# ///////////////////////////////////////////////////////////////////
#
# @remark: database interface for manager server

import logging
import mysql.connector
from conf.context import context


class Database(object):
    def __init__(self):
        self.mysql_con = None
        self.mysql_cur = None
        self.config = {
            'user': context.setting['database']['user'],
            'password': context.setting['database']['password'],
            'host': context.setting['database']['host'],
            'port': int(context.setting['database']['port']),
            'database': context.setting['database']['schema'],
            'charset': 'utf8',
            'raise_on_warnings': True
        }

    def is_connected(self):
        return not not self.mysql_cur

    def connect_db(self):
        try:
            self.mysql_con = mysql.connector.connect(**self.config)
            self.mysql_con.autocommit = True
            self.mysql_cur = self.mysql_con.cursor(dictionary=True)
            logging.info('Connect database successfully.')
            return True
        except Exception as e:
            logging.error('Fail to connect database %s' % str(e))

    def disconnect_db(self):
        if self.mysql_cur:
            self.mysql_cur.close()
            self.mysql_cur = None
        if self.mysql_con:
            self.mysql_con.close()
            self.mysql_con = None

    def execute(self, *sql):
        try:
            logging.debug('execute sql: %s' % str(sql))
            self.mysql_cur.execute(*sql)
            return True
        except Exception as e:
            if str(e).find("Duplicate") < 0:
                logging.error('execute sql exception: %s, %s' % (sql, str(e)))

    def query(self, *sql):
        try:
            if self.execute(*sql):
                return self.mysql_cur.fetchall()
        except Exception as e:
            logging.error('query exception %s, %s' % (sql, str(e)))

